import JJRequestAgent from './JJRequestAgent.js';
import { JJError } from '../bizUtil';

export default class JJBaseRequest {

    JJRequestMethod = {
        Post: "post",
        Get: "get",
    }

    // request
    methodType = this.JJRequestMethod.Post;
    parameters = {}; // 请求参数

    // response
    responseCode = -1;
    responseData = null; // 返回结果
    responseHeader = null; // 应答头
    error = null;

    networkSuccessCallBack = null;
    networkFailCallBack = null;

    isNeedPostResponseNotification = false

    otherInfo = {}

    timer;
    timeoutMillisecondInterval = 30 * 1000; // 毫秒

    // 服务器地址
    getHostUrl() {
        return ""
    }

    // 请求路径
    getPathUrl() {
        return ""
    }

    requestParameter() {
        return {}
    }

    getRequestHeader() {
        const header = {
            'content-type': 'application/x-www-form-urlencoded;charset=utf-8',
        }
        return header
    }

    getRequestCredentials() {
        return 'include'
    }

    setResponseData(response) {
        return response.json()
    }

    doBeforeStart() {
        return Promise.resolve();
    }

    requestCompleteFilter(response) {
        return Promise.resolve(response);
    }

    requestFailedFilter(error) {
        return Promise.resolve(error);
    }

    filterSuccessCallBackValue(isSuccess, value) {
        return value
    }

    filterFailCallBackValue(value) {
        return JJError.networkReuqestFailError
    }

    start(networkSuccessCallBack, networkFailCallBack) {
        this.networkSuccessCallBack = networkSuccessCallBack;
        this.networkFailCallBack = networkFailCallBack;

        const me = this
        this.doBeforeStart().then(() => {
            JJRequestAgent.sharedInstance().start(me);
        });

        // 在某些android机上，timer无效
        // this.timer = setTimeout(() => {
        //     me.stop();
        //     me.networkFailCallBack({message: '网络连接超时，等会再试~'}, me.otherInfo);
        // }, this.timeoutMillisecondInterval);
    }

    stop() {
        this.cancelTimeoutTimer()
        JJRequestAgent.shareInstance().stop(this)
    }

    buildRequestUrl() {
        let url = this.getHostUrl() + this.getPathUrl()
        return url;
    }

    cancelTimeoutTimer() {
        this.timer && clearTimeout(this.timer)
    }

    postResponseNotification(isSuccess, value, error) {
    }

    isAllowBeginUploadFile() {
        return true
    }

    isAllowBeginSendRequest() {
        return true
    }
}
